import { appUserTree, appUserTreeAdd, appUserTreeDelete, appUserTreeEdit,userProfileDisable, userProfileList, userProfileRemove, userProfileResetPassword, userProfileStatus } from "@/services/userProfile";
import { Button, Col, DatePicker, Form, Input, Modal, Row, Select, Table, message,Layout,Spin,Pagination } from "antd";
import React from "react";
import { formatMessage } from 'umi-plugin-react/locale';
import { ButtonGroup, MoreOption, TreeShape } from "@/utils/CommonComponent";
import moment from "moment";
import UpdateUser from "./updateUser";
import tableDataCheck from "@/utils/isBackPrevPage";
import BatchModal from "./batchModal";
import UserSession from "@/UserSession";

const { Header, Footer, Sider, Content } = Layout;

class AppUsers extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      optNode:{},
      currentNode:{},
      treeData:[],
      treeLoading:false,
      expandedKeys:[],

      current:1,
      size:10,
      list:[],
      total:0,
      loading:false,

      addMenuList:[
        {
          key:'add',
          name:formatMessage({ id: 'appUsers.menu.createAccount' })
        },
        {
          key:"import",
          name:formatMessage({ id: 'appUsers.menu.importUsers' })
        }
      ],

      optMenuList:[
        {
          key:'agree',
          name:formatMessage({ id: 'appUsers.menu.batchApprove' })
        },
        {
          key:'refuse',
          name:formatMessage({ id: 'appUsers.menu.batchReject' })
        },
        {
          key:'stop',
          name:formatMessage({ id: 'appUsers.menu.batchDisable' })
        },
        {
          key:'start',
          name:formatMessage({ id: 'appUsers.menu.batchEnable' })
        },
        {
          key:'delete',
          name:formatMessage({ id: 'appUsers.menu.batchDelete' })
        },
      ],
      selectedRowKeys:[],
      selectedRows:[],
      pathType:"app",
      applicationId:props.applicationId
    }
  }

  componentDidMount(){
    if(this.props.onRef){
      this.props.onRef(this)
    }
    const { applicationId,location } = this.props;
    if(location && location.pathname === '/enterpriseUserManagement'){
      const userInfo = UserSession.getCurrentUser()
      this.setState({
        pathType:"enterpriseUserManagement",
        applicationId:userInfo ? userInfo.applicationId  : ''
      },() => {
        this.getTreeData("init")
      })
    }
  }

  getTreeData = (flag) => {
    const { applicationId } = this.state;

    this.setState({
      treeLoading:true
    },async () => {
      const res = await appUserTree({applicationId});
      this.setState({
        treeLoading:false,
        treeData:res ? res : []
      },() => {
        if(flag && flag == 'init'){
          this.doInit(res)
        }
      })
    })
  }

  doInit = res => {
    this.setState({
      currentNode:res && res[0] ? res[0] : {},
      expandedKeys:res && res[0] ? [res[0].id] : []
    },() => {
      this.getTableData()
    })
  }

  //选择树
  nodeSelect = (selectedKeys,e) => {
    this.setState({
      currentNode:e.node.props.info,
      selectedKeys:[e.node.props.info.id]
    },() => {
      this.getTableData()
    })
  }

  //新增节点
  addNode = (item,name) => {
    const { expandedKeys,applicationId } = this.state;
    this.setState({
      optNode:item
    },async () => {
      const res = await appUserTreeAdd({name,parentId:item.id,applicationId})
      message.info(res.message)
      this.getTreeData()
      if(expandedKeys.indexOf(item.id) == -1){
        expandedKeys.push(item.id)
      }
      this.setState({
        optNode:{},
        expandedKeys
      })
    })
  }

  //展开收起节点
  nodeExpand = expandedKeys => {
    this.setState({expandedKeys})
  }

  //删除节点
  nodeDelete = async () => {
    const { optNode } = this.state;
    const res = await appUserTreeDelete({id:optNode.id})
    message.info(res.message)
    this.getTreeData('init')
    this.setState({
      optNode:{}
    })
  }

  //编辑节点名
  nodeUpdateName = async name => {
    const { optNode } = this.state;
    const res = await appUserTreeEdit({id:optNode.id,name,parentId:optNode.parentId})
    message.info(res.message)
    this.getTreeData()
    this.setState({
      optNode:{}
    })
  }

  //设置操作节点
  setOptNode = item => {
    this.setState({optNode:item})
  }

  //----------------------------------------------------------------------------------------------------

  doSearch = (current,size) => {
    this.setState({
      current,size
    },() => {
      this.getTableData()
    })
  }

  getTableData = () => {
    this.setState({
      loading:true
    },async () => {
      const { current,size,currentNode} = this.state;
      const info = this.props.form.getFieldsValue()
      let obj = {
        current,size,
        search:info.search,
        startTime:info.time && info.time[0] ? moment(info.time[0]).format("YYYY-MM-DD") : '',
        endTime:info.time && info.time[1] ? moment(info.time[1]).format("YYYY-MM-DD") : '',
        categoryId:currentNode.id,
        status:info.status
      }
      const res = await userProfileList(obj)
      this.setState({
        list:res.records,
        total:res.total,
        loading:false,
        selectedRowKeys:[]
      })
    })
  }

  moreMenuClick = e => {
    const { selectedRowKeys } = this.state;
    switch(e.key){
      case 'add':
        this.openAddModal(null)
        break;
      case 'import':
        this.BatchModal.openModal()
        break;
      case 'agree':
        this.changeStatus(selectedRowKeys,0)
        break;
      case 'refuse':
        this.changeStatus(selectedRowKeys,3)
        break;
      case 'stop':
        this.changeStatus(selectedRowKeys,1)
        break;
      case 'start':
        this.changeStatus(selectedRowKeys,0)
        break;
      case 'delete':
        this.removeConfirm(selectedRowKeys)
        break;
      case 'edit':
        this.openAddModal(e)

    }
  }

  openAddModal = (row) => {
    this.UpdateUser.initData(row)
  }

  removeConfirm = idList => {
    if(idList.lenght == 0){
      message.error(formatMessage({ id: 'appUsers.message.selectData' }))
      return false
    }
    const that = this
    Modal.confirm({
      title: formatMessage({ id: 'appUsers.confirm.deleteTitle' }),
      okText: formatMessage({ id: 'appUsers.confirm.ok' }),
      cancelText: formatMessage({ id: 'appUsers.confirm.cancel' }),
      okType: "danger",
      onOk() {
        that.doRemove(idList)
      }
    })
  }

  doRemove = async idList => {
    const res = await userProfileRemove({ idList })
    const { list, current, size } = this.state;
    const newCurrent = tableDataCheck(list, current, idList);
    this.doSearch(newCurrent, size)
    message.info(res.message)
  }

  resetPassword = async id => {
    const res = await userProfileResetPassword({ id })
    message.info(res.message)
  }

  changeStatus = async (idList, status) => {
    if(idList.length == 0){
      message.error("请选择需要操作的数据")
      return false
    }
    const res = await userProfileStatus({ idList, status })
    message.info(res.message)
    this.getTableData()
  }

  render(){
    const {
      optNode,
      currentNode,
      treeData,
      treeLoading,
      expandedKeys,
      current,
      size,
      total,
      list,
      loading,
      addMenuList,
      optMenuList,
      selectedRowKeys,
      pathType,
      applicationId
     } = this.state;
     const { form: { getFieldDecorator } } = this.props;
     const columns = [
      {
        title: formatMessage({ id: 'appUsers.table.index' }),
        dataIndex: "index",
        width: 60,
        render(text, row, index) {
          return (current - 1) * size + (index + 1)
        }
      },
      {
        title: formatMessage({ id: 'appUsers.table.name' }),
        dataIndex: "name",
        width: 100
      },
      {
        title: formatMessage({ id: 'appUsers.table.email' }),
        dataIndex: "email",
        width: 100
      },
       {
         title: formatMessage({ id: 'appUsers.table.mobilePhone' }),
         dataIndex: "mobilePhone",
         width: 100
       },
      {
        title: formatMessage({ id: 'appUsers.table.account' }),
        dataIndex: "phone",
        width: 100
      },
      {
        title: formatMessage({ id: 'appUsers.table.interceptCount' }),
        dataIndex: "num",
        width: 100
      },
      {
        title: formatMessage({ id: 'appUsers.table.createTime' }),
        dataIndex: "createTime",
        width: 100,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: formatMessage({ id: 'appUsers.table.lastLoginTime' }),
        dataIndex: "lastLoginTime",
        width: 110,
        render: time => {
          return time ? moment(time).format("YYYY-MM-DD HH:mm:ss") : ''
        }
      },
      {
        title: formatMessage({ id: 'appUsers.table.status' }),
        dataIndex: "status",
        width: 80,
        render(type) {
          switch (type) {
            case 0:
              return <span style={{ color: '#52c41a' }}>{formatMessage({ id: 'appUsers.status.normal' })}</span>
            case 1:
              return <span style={{ color: "red" }}>{formatMessage({ id: 'appUsers.status.disabled' })}</span>
            case 2:
              return <span style={{ color: "#3e5bff" }}>{formatMessage({ id: 'appUsers.status.applying' })}</span>
            case 3:
              return <span style={{ color: "red" }}>{formatMessage({ id: 'appUsers.status.rejected' })}</span>
          }
        }
      },
    ]
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.setState({
          selectedRowKeys,
          selectedRows
        })
      },
      selectedRowKeys
    };

    if(pathType === 'enterpriseUserManagement'){
      columns.push({
        title: formatMessage({ id: 'appUsers.table.action' }),
        width: 150,
        render: (text, row) => {
          return <div>
            {
              row.status == 0 ? (
                <ButtonGroup 
                    title={formatMessage({ id: 'appUsers.action.disable' })}
                    group="stop-table"
                    handleClick={() => this.changeStatus([row.id], 1)}
                  />
              ) : ''
            }
            {
              row.status == 1 ? (
                <ButtonGroup 
                    title={formatMessage({ id: 'appUsers.action.enable' })}
                    group="start-table"
                    handleClick={() => this.changeStatus([row.id], 0)}
                  />
              ) : ''
            }
            <ButtonGroup 
              title={formatMessage({ id: 'appUsers.action.resetPassword' })}
              group="reset-table"
              handleClick={() => this.resetPassword(row.id)}
            />
            <ButtonGroup
                title={formatMessage({ id: 'appUsers.action.edit' })}
                group="reset-table"
                handleClick={() => this.moreMenuClick({key:'edit',id:row.id,name:row.name,phone:row.phone,email:row.email,mobilePhone:row.mobilePhone})}
            />
          </div>
        }
      })
    }
     return Array.isArray(treeData) && (
      <Layout style={{height:"100%"}}>
        <Sider theme="light" width={250} style={{background:"#ffffff",borderRadius:"6px 0 0 6px",padding:10}}>
          <Spin spinning={treeLoading}>
            <TreeShape treeData={treeData}
              optNode={optNode}
              currentNode={currentNode}
              expandedKeys={expandedKeys}
              nodeSelect={this.nodeSelect}
              addNode={this.addNode}
              nodeExpand={this.nodeExpand}
              nodeDelete={this.nodeDelete}
              setOptNode={this.setOptNode}
              nodeUpdateName={this.nodeUpdateName}
            />
          </Spin>
        </Sider>
        <Content style={{background:"#ffffff",borderRadius:"0 6px 6px 0",padding:10}}>
          <div className="topOptionBox">
            <div className="topOptionBox-left">
              <Form layout="inline">
                <Form.Item>
                  {
                    getFieldDecorator("search", { initialValue: "" })(
                      <Input.Search placeholder={formatMessage({ id: 'appUsers.search.placeholder' })} onSearch={() => this.doSearch(1, size)} />
                    )
                  }
                </Form.Item>
                <Form.Item>
                  {
                    getFieldDecorator("time")(
                      <DatePicker.RangePicker style={{width:250}} onChange={() => this.doSearch(1,size)} />
                    )
                  }
                </Form.Item>
                <Form.Item>
                  {
                    getFieldDecorator("status")(
                      <Select style={{width:100}} onChange={() => this.doSearch(1,size)} placeholder={formatMessage({ id: 'appUsers.status.selectPlaceholder' })}>
                        <Select.Option value={null}>{formatMessage({ id: 'appUsers.status.all' })}</Select.Option>
                        <Select.Option value={0}>{formatMessage({ id: 'appUsers.status.normal' })}</Select.Option>
                        <Select.Option value={1}>{formatMessage({ id: 'appUsers.status.disabled' })}</Select.Option>
                      </Select>
                    )
                  }
                </Form.Item>
              </Form>
            </div>
            {
              pathType != 'enterpriseUserManagement' ? '' : (
                <div className="topOptionBox-right">
                  <Button type="primary" onClick={() => this.moreMenuClick({key:'add'})} style={{marginRight:8}}>{formatMessage({ id: 'appUsers.button.createAccount' })}</Button>
                  <Button type="danger" onClick={() => this.moreMenuClick({key:'delete'})}>{formatMessage({ id: 'appUsers.button.deleteAccount' })}</Button>
                </div>
              )
            }
          </div>

          <Table
            dataSource={list}
            loading={loading}
            rowKey='id'
            pagination={false}
            scroll={{ x: "auto", y: 'calc(100vh - 380px)' }}
            columns={columns}
            rowSelection={pathType != 'enterpriseUserManagement' ? false : rowSelection}
          />
          {parseInt(total) > 10 ? (
            <Pagination
              showQuickJumper
              total={total}
              current={current}
              onChange={this.doSearch}
              style={{ textAlign: 'right', marginTop: 16 }}
            />
          ) : null}

        </Content>

        <UpdateUser
          onRef={ref => this.UpdateUser = ref}
          applicationId={applicationId}
          refershList={() => this.doSearch(1, size)}
          currentNode={currentNode}
          pathType={pathType}
        />
        <BatchModal
          onRef={ref => this.BatchModal = ref}
          applicationId={applicationId}
          refreshList={() => this.doSearch(1, size)}
        />
      </Layout>
     )
  }
}

export default Form.create()(AppUsers)